package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.TagBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.util.EmojiFilter;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.materialedittext.MaterialEditText;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by heshantao on 15/7/1.
 * 个人标签设置
 */
@EActivity(R.layout.activity_personal_tag_set)
public class PersonalTagSetActivity extends ZlineActivity {
    private static final String LOG_TAG = PersonalTagSetActivity.class.getSimpleName();
    //标题
    @StringRes(R.string.personal_tag)
    String title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.tag1_rl)
    RelativeLayout tag1_rl;
    @ViewById(R.id.tag1_set_mtv)
    MaterialEditText tag1_mtv;
    @ViewById(R.id.tag2_rl)
    RelativeLayout tag2_rl;
    @ViewById(R.id.tag2_set_mtv)
    MaterialEditText tag2_mtv;
    @ViewById(R.id.tag3_rl)
    RelativeLayout tag3_rl;
    @ViewById(R.id.tag3_set_mtv)
    MaterialEditText tag3_mtv;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    //来源类型：1-用户,2-项目,3-商品
    @Extra
    int resourceType;
    //来源Id：用户Id,项目Id,商品Id
    @Extra
    long resourceId;
    SparseArray<TagBean> tagBeanSparseArray;
    String tag1,tag2,tag3;
    final int tagMaxCharacter=8;
    @Bean
    NetworkUtil networkUtil;

    @AfterViews
    void doSomeAfterViews() {
        getTags();
        initView();
    }

    void initView() {
        title_tv.setText(title);
        tag1_rl.setTag(true);
        tag2_rl.setTag(false);
        tag3_rl.setTag(false);

    }


    //获得用户标签
    void getTags() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            httpOperator.requstTagsInfo(httpUtil, resourceType, resourceId, requestTagsHandler);
        } else {
            TUtil.showShort(this, R.string.no_network);
        }
    }


    //获取标签回调
    AsyncHttpResponseHandler requestTagsHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestTagsHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        tagBeanSparseArray=httpDataParsing.getTagList(response);
                        setTags(tagBeanSparseArray);

                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            dissLoadingDialog();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };

    //设置标签
    void setTags(SparseArray<TagBean> tags){
           TagBean tagBean1=tags.get(0);
            if(tagBean1!=null){
                tag1_mtv.setText(tagBean1.getContent());
                tag1_rl.setTag(true);
            }
            TagBean tagBean2=tags.get(1);
            if(tagBean2!=null){
                tag2_mtv.setText(tagBean2.getContent());
                tag2_rl.setTag(true);
                tag2_rl.setVisibility(View.VISIBLE);
            }

            TagBean tagBean3=tags.get(2);
            if(tagBean3!=null){
                tag3_mtv.setText(tagBean3.getContent());
                tag3_rl.setTag(true);
                tag3_rl.setVisibility(View.VISIBLE);
            }
    }


    //添加标签
    void addTag() {
        boolean bool1 = (boolean) tag1_rl.getTag();
        boolean bool2 = (boolean) tag2_rl.getTag();
        boolean bool3 = (boolean) tag3_rl.getTag();
        LUtil.i(LOG_TAG, "______1____" + bool1 + "______2____" + bool2 + "______3____" + bool3);
        if(bool1&&bool2&&bool3){
            TUtil.showShort(this, R.string.tag_add_limit);
            return;
        }
        if (!bool1) {
            tag1_rl.setVisibility(View.VISIBLE);
            tag1_rl.setTag(true);
            return;
        } else if (!bool2) {
            tag2_rl.setVisibility(View.VISIBLE);
            tag2_rl.setTag(true);
            return;
        } else if (!bool3) {
            tag3_rl.setVisibility(View.VISIBLE);
            tag3_rl.setTag(true);
            return;
        }

    }


    //存储标签
    void saveTags(){
        tag1=tag1_mtv.getText().toString().trim();
        //tag1= EmojiFilter.filterEmoji(tag1);
        tag2=tag2_mtv.getText().toString().trim();
        //tag2= EmojiFilter.filterEmoji(tag2);
        tag3=tag3_mtv.getText().toString().trim();
        //tag3= EmojiFilter.filterEmoji(tag3);
        List<String> tags=new ArrayList<String>();
        if(!StringUtils.isBlank(tag1)){
            tags.add(tag1);
        }

        if(!StringUtils.isBlank(tag2)){
            tags.add(tag2);
        }

        if(!StringUtils.isBlank(tag3)){
            tags.add(tag3);
        }

        if(tag1.length()>tagMaxCharacter||tag2.length()>tagMaxCharacter||tag3.length()>tagMaxCharacter){
            TUtil.showLong(this,R.string.tag_character_limit);
            return;
        }

        JsonObject jsonObject,tagJson;
        JsonArray jsonArray=new JsonArray();
        if(tags.size()!=0){
            for(String tag:tags){
                jsonObject=new JsonObject();
                jsonObject.addProperty(Constant.TAG_CONTENT,tag);
                jsonArray.add(jsonObject);
            }
        }
        tagJson=new JsonObject();
        tagJson.add(Constant.TAG_DTO_LIST, jsonArray);

        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            httpOperator.requstSaveTagsInfo(httpUtil,tagJson,saveTagsHandler);
        } else {
            TUtil.showShort(this, R.string.no_network);
        }
    }


    //存储标签回调
    AsyncHttpResponseHandler saveTagsHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____saveTagsHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        tagBeanSparseArray=httpDataParsing.getTagList(response);
                        setResult(tagBeanSparseArray);

                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            LUtil.i(LOG_TAG, "____failure__________" + responseString.toString());
        }
    };

    void setResult(SparseArray<TagBean> tagBeans){
        Intent intent=new Intent();
        Bundle bundle=new Bundle();
        String tags="";
        for(int i=0;i<tagBeans.size();i++){
            tags+="#"+tagBeans.get(i).getContent().toString()+"#";
        }
        bundle.putString(Constant.VALUE,tags);
        intent.putExtras(bundle);
        setResult(Constant.TAG_RESULT_CODE, intent);
        finish();
    }


    @Click({R.id.tag1_set_cut_iv, R.id.tag2_set_cut_iv,R.id.tag_save_btn,
            R.id.tag3_set_cut_iv, R.id.tag_set_add_iv,
            R.id.app_common_header_left_icon_iv
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tag1_set_cut_iv:
                tag1_rl.setVisibility(View.GONE);
                tag1_mtv.setText("");
                tag1_rl.setTag(false);
                break;
            case R.id.tag2_set_cut_iv:
                tag2_rl.setVisibility(View.GONE);
                tag2_mtv.setText("");
                tag2_rl.setTag(false);
                break;
            case R.id.tag3_set_cut_iv:
                tag3_rl.setVisibility(View.GONE);
                tag3_mtv.setText("");
                tag3_rl.setTag(false);
                break;
            case R.id.tag_set_add_iv:
                addTag();
                break;
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.tag_save_btn:
                saveTags();
                break;
            default:
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
